package myfile

import (
	"os"
	"path"
	"strings"

	"github.com/gen2brain/go-unarr"
)

var tmpbuilder strings.Builder

func init() {

	tmpbuilder.Grow(20480)
}

func Filefound(fpath string) error {
	flag, _ := IsDir(fpath)
	switch flag {
	case 1:
		{
			files, err := os.ReadDir(fpath)
			if err != nil {
				return err
			}
			for _, file := range files {
				tmpbuilder.Reset()
				tmpbuilder.WriteString(fpath + "/" + file.Name())

				Filefound(tmpbuilder.String())

				//
			}
		}
	case 0:
		{
			//fmt.Printf("\n %s", fpath)
			Extract(tmpbuilder.String())
		}
	}

	return nil
}
func Extract(fpath string) {
	ftype := path.Ext(fpath)
	var Edir string
	Edir = strings.Clone(fpath[0 : len(fpath)-len(ftype)])

	//	ftype := fpath[0 : len(fpath)-len(Edir)]
	switch ftype {
	case ".rar", ".zip", ".7z", ".tar", ".RAR", ".7Z", ".TAR", ".ZIP":
		a, err := unarr.NewArchive(fpath)
		if err != nil {
			panic(err)
		}
		defer a.Close()
		_, err = a.Extract(Edir)
		if err != nil {
			panic(err)
		}

	}

}
func IsDir(fpath string) (int, error) {
	info, err := os.Stat(fpath)
	if err != nil {
		return 3, err
	}
	if info.IsDir() {
		return 1, nil
	}
	return 0, nil
}
